package controller;

import dao.GoodDao;
import dao.impl.GoodDaoImpl;
import domain.Goods;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

/**
 * @author HLF
 * @version V1.0
 * @package controller
 * @date 2021/10/31 20:30
 */
public class GoodsController extends BaseController {
    private GoodDao dao = new GoodDaoImpl();

    /**
     * 在商品信息管理中展示所有商品
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void allGoods(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Goods> goodsManage = dao.queryGoods();
        req.setAttribute("goodsManage", goodsManage);
        req.getRequestDispatcher("/pages/admin/goodsManage.jsp").forward(req, resp);
    }


    /**
     * 删除商品操作
     */
    protected void deleteGoods(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer id = Integer.valueOf(req.getParameter("id"));
        int i = dao.deleteGoodsById(id);
        if (i > 0) {
            req.getRequestDispatcher("/admin/goodsController?action=allGoods").forward(req, resp);
        }
    }

    /**
     * 添加操作
     */
    protected void addGoods(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String gname = req.getParameter("gname");
        BigDecimal gprice = new BigDecimal(req.getParameter("gprice"));
        Integer gnum = Integer.valueOf(req.getParameter("gnum"));
        String gimg = req.getParameter("gimg");
        Goods goods = new Goods(null, gname, gprice, gnum, gimg);
        int i = dao.addGoods(goods);
        if (i > 0) {
            req.getRequestDispatcher("/admin/goodsController?action=allGoods").forward(req, resp);
        }
    }

    /**
     * 添加商品并上传图片（非路径）
     * 使用JavaWeb中文件的上传
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void addGoods2(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String gname = null;
        BigDecimal gprice = null;
        Integer gnum = null;
        String gimg = null;
        try {
            //1.判断当前上传的数据格式是否是多段的格式。
            if (ServletFileUpload.isMultipartContent(req)) {
                //创建FileItemFactory工厂实现类
                FileItemFactory fileItemFactory = new DiskFileItemFactory();
                //创建用于解析和上传数据的工具类ServletFileUpload
                ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
                try {
                    //2.解析上传的数据,得到每一个表单项FileItem
                    List<FileItem> list = servletFileUpload.parseRequest(req);
                    //3.循环判断每一个表单项，是普通表单项还是上传文件表单项
                    for (FileItem fileItem : list) {
                        if (fileItem.isFormField()) {//普通表单项
                            if ("gname".equals(fileItem.getFieldName())) {
                                gname = fileItem.getString("UTF-8");
                            } else if ("gnum".equals(fileItem.getFieldName())) {
                                gnum = Integer.valueOf(fileItem.getString("UTF-8"));
                            } else if ("gprice".equals(fileItem.getFieldName())) {
                                gprice = new BigDecimal(fileItem.getString("UTF-8"));
                            }
                        } else {//上传文件表单项
                            //4.将上传的文件写入磁盘(写入tomcat的路径)
                            fileItem.write(new File("D:\\JavaWeb\\HfsSale\\target\\HfsSale-1.0-SNAPSHOT\\imgs\\"
                                    + gname + ".jpg"));
                        }
                    }
                    //5.执行插入语句
                    Goods goods = new Goods(null, gname, gprice, gnum, "./imgs/" + gname + ".jpg");
                    int i = dao.addGoods(goods);
                    if (i > 0) {
                        req.getRequestDispatcher("/admin/goodsController?action=allGoods").forward(req, resp);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改商品
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void updateGoods(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer id = Integer.valueOf(req.getParameter("id"));
        Goods goods = dao.queryGoodsById(id);
        req.setAttribute("idGoods", goods);
        req.getRequestDispatcher("/pages/admin/goodsUpdate.jsp").forward(req, resp);
    }

    protected void updateGoods2(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer id = Integer.valueOf(req.getParameter("id"));
        String name = req.getParameter("name");
        BigDecimal price = new BigDecimal(req.getParameter("price"));
        Integer num = Integer.valueOf(req.getParameter("num"));
        String img = req.getParameter("img");
        Goods goods = new Goods(id, name, price, num, img);
        int i = dao.updateGoods(goods);
        if (i > 0) {
            resp.sendRedirect("/HfsSale/admin/goodsController?action=allGoods&i=" + i);
        }
    }

    /**
     * 通过名字查询商品
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void queryGoodsByName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        List<Goods> list = dao.queryGoodsByName(name);
        req.setAttribute("nameGoods", list);
        req.getRequestDispatcher("/pages/index/nameGoods.jsp").forward(req, resp);
    }

    /**
     * 通过指定的价格区间查询商品
     */
    protected void queryGoodsByPrice(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String min = req.getParameter("minPrice");
        String max = req.getParameter("maxPrice");
        if (min == null || "".equals(min)) {
            min = "0";//当用户未输入时，默认的最小价格
        }
        if (max == null || "".equals(max)) {
            max = "99999";//当用户未输入价格是默认的最大价格
        }
        BigDecimal minPrice = new BigDecimal(min);
        BigDecimal maxPrice = new BigDecimal(max);
        List<Goods> list = dao.queryGoodsByPrice(minPrice, maxPrice);
        req.setAttribute("nameGoods", list);
        req.getRequestDispatcher("/pages/index/nameGoods.jsp").forward(req, resp);
    }
}
